<template>
  <section>
    <div class="title">产品规格设置</div>
    <div class="spec-line" v-for="(item, index) in specData" :key="index">
      <div class="pb10">
        <el-select
          v-model="specData[index].specsUid"
          placeholder="请选择商品规格"
          size="small"
          class="input-rule"
        >
          <el-option
            v-for="specs in specsOptions"
            :key="specs.specsUid"
            :label="specs.specsName"
            :value="specs.specsUid"
            @click.native="handleSave(specs.specsName, index)"
          />
        </el-select>
      </div>
      <div>
        <el-tag
          v-for="(tag, j) in item.values"
          :key="j"
          @close="delSpecTag(index, j)"
          closable
          >{{ tag.text }}</el-tag
        >
        <el-input
          style="width: 270px"
          size="small"
          placeholder="多个属性用空格隔开"
          v-model="addValues[index]"
          @keyup.native.enter="handleAddTag(index)"
        >
          <el-button
            slot="append"
            icon="el-icon-check"
            type="primary"
            @click="handleAddTag(index)"
          ></el-button>
        </el-input>
      </div>
      <i
        class="icon el-icon-circle-close spec-deleted"
        @click="handlerDel(index)"
      ></i>
      <el-divider></el-divider>
    </div>
    <div class="add-spec">
      <el-button
        size="small"
        type="primary"
        :disabled="specData.length >= 3"
        @click="handleAdd"
        >添加规格</el-button
      >
    </div>
  </section>
</template>

<script type="text/ecmascript-6">
import specMixins from "./mixins";
import { objEquals } from "./fn";
import { bulidSpecsSelect } from "@/api/product/specs";
import { listInfo } from "../../api/product/info";
export default {
  data() {
    return {
      addValues: [],
      cachespecData: [],
      // 商品规格
      specsOptions: [],
      specsName: "",
    };
  },
  mixins: [specMixins],
  created() {
    this.bulidSelect();
  },
  watch: {
    specData: {
      handler(data) {
        if (data && data.length > 0) this.$emit("change-data", data);
      },
      deep: true,
      immediate: true,
    },
    specTable: {
      handler(data) {
        if (data && data.length > 0) this.$emit("change-table", data);
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    stockSpecArr() {
      return this.specTable.map((item) => item.data);
    },
  },
  methods: {
    clearName(index) {
      this.specData[index].specsName = "";
    },
    // 规格
    bulidSelect() {
      // 规格
      let specs = {
        dataStatus: "1",
        dataPriority: "0",
        pageNum: 1,
        pageSize: 1000,
      };
      bulidSpecsSelect(specs).then((respone) => {
        this.specsOptions = respone.data;
      });
    },
    // 添加
    handleAdd() {
      if (this.specData.length < 5) {
        const id = Date.now();

        this.specsOptions.push({ id, text: "", status: true });
        this.specData.push({ id, specsName: "", values: [] });
      }
    },
    handleSave(specsName, index) {
      this.specsName = specsName;
      if (!specsName) {
        this.$message.error("规格不能为空！");
        return;
      }
      if (this.specData[index].specsName == specsName) {
      } else {
        if (this.verifyRepeat(index, specsName)) {
          this.$message.error("规格重复！重新选择");
          this.specsName = null;
        } else {
          // this.specData[index].specsName = specsName;
        }
      }
    },

    // 添加规格
    handleAddTag(index) {
      if (this.specData[index].specsName == null) {
        this.$message.error("规格重复！重新选择！");
        return;
      }

      let str = this.addValues[index] || "";
      if (!str.trim() && this.specData[index].values.length == 0) {
        this.$message.error("属性不能为空！");
        return;
      }
      str = str.trim();
      let arr = str.split(/\s+/);
      let tempArr = [];
      const id = Date.now();
      arr.forEach((item) => {
        tempArr.push({ id, text: item });
      });
      let newArr = this.specData[index].values.concat(tempArr);
      newArr = Array.from(new Set(newArr));
      let flag = false;
      this.specData[index].values.forEach((item) => {
        arr.forEach((i) => {
          if (item.text == i) flag = true;
        });
      });
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] == arr[i + 1]) {
          flag = true
        }
      }
      if (flag) {
        this.$message.error("属性重复！重新输入");
        return;
      }
      if (this.specsName == null && this.specTable[0].data.length >= 1) {
        this.specsName = this.specData[index].specsName;
      }
      if (this.specsName == null || this.specsName == "") {
        this.$message.error("请选择规格");
      } else {
        this.specData.forEach((i) => {
          if (this.specTable[0].data.length == 1) {
            this.specData[index].specsName = this.specsName;
            this.$set(this.specData[index], "values", newArr);
            return;
          } else if (i.specsName != this.specsName) {
            this.specData[index].specsName = this.specsName;
            this.$set(this.specData[index], "values", newArr);
            return;
          }
        });
      }
      this.specsName = null;
      this.clearAddValues(index);
      this.specChange("add");
      // this.specData[index].specsName = this.specsOptions[index].specsName;
    },
    // 删除
    delSpecTag(index, num) {
      const sd = this.specData[index].values[num];
      this.$confirm(`是否删除【${sd.text}】规格？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.specData[index].values.splice(num, 1);
          if (this.specData[index].values.length <= 0) {
            this.specData.splice(index, 1);
            // this.specsOptions.splice(index, 1);
          }
          this.specChange("del");

          this.$message({ type: "success", message: "删除成功!" });
        })
        .catch((err) => {});
    },
    handlerDel(index) {
      const sd = this.specData[index];
      this.$confirm(`是否删除【${sd.specsName}】产品规格？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.specData.splice(index, 1);
          this.specChange("del");
          this.specsName = null;
          this.addValues = []
          this.$message({ type: "success", message: "删除成功!" });
        })
        .catch((err) => {});
    },
    verifyRepeat(index, specsName) {
      let flag = false;
      this.specData.forEach((v, j) => {
        if (index !== j) {
          if (this.specData[j].specsName === specsName) flag = true;
        }
      });
      return flag;
    },
    // 删除
    clearAddValues(index) {
      this.$set(this.addValues, index, "");
    },
    specChange(option) {
      const stockCopy = this.specTable;
      if (option === "del") {
        this.specTable = [];
      }
      for (let i = 0; i < this.SKUNums; i++) {
        this.changeStock(option, i, stockCopy);
      }
    },
    // 动态更改库存相关信息
    changeStock(option, index, stockCopy) {
      const spec = this.getSpecId(index);
      if (option === "add") {
        let len = this.stockSpecArr.length;
        if (len) {
          for (let i = 0; i < len; i++) {
            if (!objEquals(spec, this.stockSpecArr[i])) {
              this.$set(this.specTable, index, this.creatChildProduct(index));
              return;
            }
          }
        } else {
          this.$set(this.specTable, index, this.creatChildProduct(index));
        }
      } else if (option === "del") {
        let origin = "";
        let len = stockCopy.length;
        for (let i = 0; i < len; i++) {
          if (objEquals(spec, stockCopy[i].data)) origin = stockCopy[i];
        }
        this.specTable.push(origin || this.creatChildProduct(index));
      }
    },
    // 获取 specTable
    getSpecId(index) {
      let obj = {};
      this.specData.forEach((item, specIndex) => {
        obj[item.text] = this.getSpecAttr(specIndex, index);
      });
      return obj;
    },
    getSpecData(index) {
      let tempArr = [];
      this.specData.forEach((item, specIndex) => {
        tempArr.push({
          id: item.specsUid,
          text: item.specsName,
          value_id: item.id,
          value_name: this.getSpecAttr(specIndex, index),
        });
      });
      return tempArr;
    },
    // 规格
    creatChildProduct(index) {
      let childProduct = {};
      childProduct["id"] = this.specTable.id;
      childProduct["data"] = this.getSpecData(index);
      childProduct["isUse"] = true;
      childProduct["picArr"] = [];
      this.thList.forEach((item) => {
        if (item.form == "bianhao") {
          childProduct["bianhao"] = this.defaultProductNo + index;
        } else {
          if (item.form == "pic") {
            childProduct["pic"] = [];
          } else {
            childProduct[item.form] = "";
          }
        }
      });
      return childProduct;
    },
  },
};
</script>

<style scoped>
.input-rule {
  width: 215px;
}
.el-input {
  width: 290px;
}
.spec-deleted {
  position: absolute;
  right: 0;
  top: 0;
  display: none;
  cursor: pointer;
}
.el-tag {
  margin-right: 3px;
}
.spec-line {
  position: relative;
}
:hover .spec-deleted {
  display: inline;
}
.title {
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}
.pb10 {
  padding-bottom: 10px;
}
.smallinput {
  width: 245px;
}
</style>
